package com.jfinal.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RuntimeUtil;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * PDF 工具类
 * 使用该工具类，需要安装 libreoffice，并配置环境变量
 * 下载地址：
 * https://zh-cn.libreoffice.org/download/libreoffice/
 */
public class PdfUtil {

    /**
     * 转 PDF
     *
     * @param filePath     原文件路径 本地路径
     * @param targetFolder 目标文件夹
     */
    public static boolean officeToPdf(String filePath, String targetFolder) {
        long start = System.currentTimeMillis();
        String srcPath = filePath, desPath = targetFolder;
        System.out.println("源文件：" + filePath);
        System.out.println("目标文件夹：" + targetFolder);
        String command = "";
        String osName = System.getProperty("os.name");
        System.out.println("系统名称：" + osName);
        // String[] cmd = {"cmd", "/k", command};
        if (osName.contains("Windows")) {
            command = "soffice --headless --convert-to pdf " + srcPath + " --outdir " + desPath;
        } else {
            command = "libreoffice7.0 --convert-to pdf:writer_pdf_Export " + srcPath + " --outdir " + desPath;
        }

        try {
            String resultStr = RuntimeUtil.execForStr(command);
            System.out.println(resultStr);
        } catch (Exception e) {
            return false;
        }

        long end = System.currentTimeMillis();
        System.out.println("转换文件耗时：" + (end - start) + "毫秒");

        return true;
    }


    /**
     * PDF文件转PNG图片，全部页数
     *
     * @param pdfFilePath  pdf文件路径 物理路径
     * @param dstImgFolder 图片存放的文件夹
     * @param dpi          dpi越大转换后越清晰，相对转换速度越慢 dpi为96,100,105,120,150,200中,105显示效果较为清晰,体积稳定,dpi越高图片体积越大,一般电脑显示分辨率为96
     * @return
     */
    public static List<String> pdfToImage(String pdfFilePath, String dstImgFolder, Integer dpi) {
        if (dpi == null) dpi = 96;
        List<String> pathArray = new ArrayList<>();

        int pages = 1;
        PDDocument pdDocument;
        try {
            FileUtil.mkdir(dstImgFolder);

            File file = new File(pdfFilePath);
            while (!file.exists()) {
                System.out.println("文件未生成，等待1秒");
                Thread.sleep(1000);
            }
            pdDocument = PDDocument.load(file);
            int dot = pdfFilePath.lastIndexOf('.');
            int lastSep = pdfFilePath.lastIndexOf(File.separator) + 1;
            String imagePDFName = pdfFilePath.substring(lastSep, dot); // 获取图片文件名

            PDFRenderer renderer = new PDFRenderer(pdDocument);
            /* dpi越大转换后越清晰，相对转换速度越慢 */
            pages = pdDocument.getNumberOfPages();
            StringBuffer imgFilePath = null;
            for (int i = 0; i < pages; i++) {
                String imgFilePathPrefix = dstImgFolder + File.separator + imagePDFName;
                imgFilePath = new StringBuffer();
                imgFilePath.append(imgFilePathPrefix);
                imgFilePath.append("_");
                imgFilePath.append(String.valueOf(i + 1));
                imgFilePath.append(".png");
                File dstFile = new File(imgFilePath.toString());
                BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                ImageIO.write(image, "png", dstFile);

                pathArray.add(FileUtil.getAbsolutePath(dstFile));
            }
            System.out.println("PDF文档转PNG图片成功！");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return pathArray;
    }

    public static void main(String[] args) throws IOException {
        PdfUtil.officeToPdf("D:\\01.xlsx", "D:\\");
    }
}
